package com.bear.sgg.springboot_08_jdbc.config;

import com.alibaba.druid.filter.stat.StatFilter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassNmae DruidConfig
 * @Description 配置Druid数据源
 * 在application.yaml文件中配置的数据源信息默认会映射到class com.zaxxer.hikari.HikariDataSource数据源实例中，
 * 为了使用Druid数据源，我们需要将该数据源实例放入到spring boot的容器中，并映射到相应的application.yml文件中，
 * 此外还需要为Druid数据源配置相应的servlet和filter以便来访问Druid提供的监控后台。
 * @Author bear
 * @Date 2020/3/14 0014 下午 3:28
 */
@Configuration
public class DruidConfig {

    /**
     * 配置DruidDataSource实例
     * 通过@Bean注解加入到spring容器中
     * 通过@ConfigurationProperties注解将application.properties文件中spring.datasource的各种配置值映射到实例中
     * @return
     */
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid() {
        return new DruidDataSource();
    }

    /**
     * 配置druid监控平台的servlet，可以通过/druid/访问到该监控平台
     * @return
     */
    @Bean
    public ServletRegistrationBean<StatViewServlet> servletRegistrationBean() {
        ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        //修改Servlet的初始化参数，这些参数定义在ResourceServlet.class中
        Map<String, String> params = new HashMap<>();
        params.put("loginUsername", "admin");       //监控平台的用户名
        params.put("loginPassword", "123456");      //监控平台的密码
        params.put("allow", "");                    //白名单（默认允许所有访问）
        params.put("deny", "192.168.0.0");          //黑名单
        registrationBean.setInitParameters(params);
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean<WebStatFilter> filterRegistrationBean() {
        FilterRegistrationBean<WebStatFilter> registrationBean = new FilterRegistrationBean<>();
        Map<String, String> params = new HashMap<>();
        params.put("exclusions", "*.js,*.css,*.jpg,*.png,*.ico,/druid/*");     //定义不过滤的路径
        registrationBean.setFilter(new WebStatFilter());
        registrationBean.setInitParameters(params);
        registrationBean.setUrlPatterns(Arrays.asList("/**"));    //定义需要进行过滤的路径
        return registrationBean;
    }
}
